﻿//#define DEBUG_MY

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Diagnostics;
using System.Threading;
using System.IO;
namespace EventLogCSharp
{
	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();

            Thread threadOfWatting = new Thread(new ThreadStart(theadOfWaittingFunc))
            {
                IsBackground = true	//默认为前台线程
            };
            threadOfWatting.Start();

#if  !DEBUG_MY
            showEventLogToListView();
#endif
            timer1.Start();
            fw.Dispose();
            threadOfWatting.Abort();

            this.TopMost = true;


		}


		FormWaitting fw = new FormWaitting();
		void theadOfWaittingFunc()
		{
			fw = new FormWaitting();
			fw.ShowDialog();
		}

		/// <summary>
		/// 获取服务器工作时间
		/// </summary>
		public string WorkTime
		{
			get
			{
				TimeSpan ts = new TimeSpan(0, 0, 0, 0, Environment.TickCount);
				return (ts.Days == 0 ? "" : (ts.Days.ToString() + "天"))
					+ (ts.Hours == 0 ? "" : (ts.Hours.ToString() + "小时" ))
					+ ts.Minutes.ToString("00") + "分钟" + ts.Seconds.ToString("00") + "秒";
			}
		}

		TimeSpan tsTotal = new TimeSpan();
		private void showEventLogToListView()
		{
			listViewShow.Items.Clear();
			tsTotal = new TimeSpan(0, 0, 0, 0, Environment.TickCount);
            labelTimeContinue.Text = tsTotal.Days.ToString() + "天" + tsTotal.Hours.ToString() + "小时" + tsTotal.Minutes.ToString() + "分钟" + tsTotal.Seconds.ToString() + "秒";

            
            if (bIsFirstStart)
            {
                EventLogOfSystem eve = new EventLogOfSystem();
                eve.GetRecords(new int[] { EventLogOfSystem.EventCode.Start, EventLogOfSystem.EventCode.Shutdown });

                showListToListView(eve.m_listStructDataOfEventLog);
            }
		}

		/// <summary>
		/// 将内存中的记录显示到listView上
		/// </summary>
		/// <param name="list"></param>
        void showListToListView(List<GLOBALMETHOD.classOfListViewRecords> list)
		{
			listViewShow.Items.Clear();
			int iOnOffTimes = 0;
            //序号
			int iSum = 0;   
			DateTime dt = new DateTime();
			tsTotal = new TimeSpan(0, 0, 0, 0, Environment.TickCount);
			bool bIsON = false;
			foreach (var v in list)
			{
				if (v.a_eventID.Equals("开机"))
				{
					
					listViewShow.Items.Add(new ListViewItem(GLOBALMETHOD.classOfListViewRecords.ConvertStructToStringArray(v) ));
					if (v.e_context.Equals("非正常关机"))
					{
						listViewShow.Items[listViewShow.Items.Count - 1].BackColor = System.Drawing.Color.LightGray;
					}

					listViewShow.Items[listViewShow.Items.Count - 1].ForeColor = System.Drawing.Color.Green;

					iSum++;
					listViewShow.Items[listViewShow.Items.Count - 1].SubItems[5].Text = iSum.ToString();

					dt = GLOBALMETHOD.classOfListViewRecords.ConvertStringToDateTime(v.b_timeGenerated);
					bIsON = true;
				}
				else if (v.a_eventID.Equals("关机"))
				{
					listViewShow.Items.Add(new ListViewItem(GLOBALMETHOD.classOfListViewRecords.ConvertStructToStringArray(v) ));
					if (v.e_context.Equals("非正常开机"))
					{
						listViewShow.Items[listViewShow.Items.Count - 1].BackColor = System.Drawing.Color.LightGray;
					}

					listViewShow.Items[listViewShow.Items.Count - 1].ForeColor = System.Drawing.Color.Red;

					iSum++;
					listViewShow.Items[listViewShow.Items.Count - 1].SubItems[5].Text = iSum.ToString();

					if (bIsON)
					{
						TimeSpan ts = GLOBALMETHOD.classOfListViewRecords.ConvertStringToDateTime(v.b_timeGenerated).Subtract(dt);
						tsTotal += ts;
						iOnOffTimes++;
					}
				}
			}

            labelOnOffTimes.Text = "开关机次数:" + iOnOffTimes.ToString();
			if (listViewShow.Items.Count > 0)
			{
				listViewShow.Items[listViewShow.Items.Count - 1].EnsureVisible();
			}
			
        }

        /// <summary>
        /// 初始状态将事件日志中的显示到listView，然后会根据这个表来合并文件中的list
        /// </summary>
        /// <param name="list"></param>
        void showListToListView(List<EventLogCSharp.EventLogOfSystem.structDataOfEventLog> list)
        {
            listViewShow.Items.Clear();
            int iOnOffTimes = 0;
			bool bIsLastStart = false;
			bool bIsLastShutdown = true;
			DateTime dt = new DateTime();
            foreach (var v in list)
			{
				if (v.EventID == EventLogOfSystem.EventCode.Start)
				{
					//MessageBox.Show("开机：" + v.timeGenerated.ToString());

					if (bIsLastShutdown && !bIsLastStart)
					{

						listViewShow.Items.Add(new ListViewItem(new string[] { "开机", v.timeGenerated.ToString("yyyy-M-d HH:mm:ss"), System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(v.timeGenerated.DayOfWeek), "" ,"",""}));
						listViewShow.Items[listViewShow.Items.Count - 1].ForeColor = System.Drawing.Color.Green;

					}
					else
					{
						listViewShow.Items.Add(new ListViewItem(new string[] { "开机", v.timeGenerated.ToString("yyyy-M-d HH:mm:ss"), System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(v.timeGenerated.DayOfWeek), "", "" ,""}));
						listViewShow.Items[listViewShow.Items.Count - 1].ForeColor = System.Drawing.Color.Green;
						if (listViewShow.Items.Count - 2 >= 0)
						{
							listViewShow.Items[listViewShow.Items.Count - 2].BackColor = System.Drawing.Color.LightGray;
							listViewShow.Items[listViewShow.Items.Count - 2].SubItems[4].Text = "非正常关机";
						}

					}
					bIsLastStart = true;
					bIsLastShutdown = false;
					dt = v.timeGenerated;
				}
				else
				{
					if (bIsLastStart && !bIsLastShutdown)
					{
						TimeSpan ts = v.timeGenerated.Subtract(dt);
						listViewShow.Items.Add(new ListViewItem(new string[] { "关机", v.timeGenerated.ToString("yyyy-M-d HH:mm:ss"), System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(v.timeGenerated.DayOfWeek), ts.ToString(), "","" }));
						listViewShow.Items[listViewShow.Items.Count - 1].ForeColor = System.Drawing.Color.Red;
						iOnOffTimes++;

						tsTotal += ts;
					}
					else
					{
						listViewShow.Items.Add(new ListViewItem(new string[] { "关机", v.timeGenerated.ToString("yyyy-M-d HH:mm:ss"), System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(v.timeGenerated.DayOfWeek), "", "","" }));
						listViewShow.Items[listViewShow.Items.Count - 1].ForeColor = System.Drawing.Color.Red;
						if (listViewShow.Items.Count - 2 >= 0)
						{
							listViewShow.Items[listViewShow.Items.Count - 2].BackColor = System.Drawing.Color.LightBlue;
							listViewShow.Items[listViewShow.Items.Count - 2].SubItems[4].Text = "非正常开机";
						}

					}
					bIsLastStart = false;
					bIsLastShutdown = true;

				}
			}

            labelOnOffTimes.Text = "开关机次数:" + iOnOffTimes.ToString();
			if (listViewShow.Items.Count > 0)
			{
				listViewShow.Items[listViewShow.Items.Count - 1].EnsureVisible();
			}
			
        }

		bool bIsFirstStart = true;
		private void timer_show(object sender, EventArgs e)
		{
			if (bIsFirstStart)
            {
                addListViewToList();
                readListFromFile();
                combineListViewAndFileList();

                showListToListView(listStructOfWriteToFile);

				bIsFirstStart = false;
				TopMost = false;
			}

			labelRunningTime.Text = WorkTime;
			tsTotal = tsTotal.Add(new TimeSpan(0, 0, 1));
             labelTimeContinue.Text = tsTotal.Seconds == 0 ? "":(tsTotal.Days.ToString() + "天") 
				+ tsTotal.Hours.ToString("00") + "小时" 
				+ tsTotal.Minutes.ToString("00") + "分钟" 
				+ tsTotal.Seconds.ToString("00") + "秒";

			showExceptionPowerTimes();
		}

        string strFilePath = Directory.GetCurrentDirectory() + "\\EventLogCSharpRecords.txt";
        //记录listview中的items
        List<GLOBALMETHOD.classOfListViewRecords> listStructOfListView = new List<GLOBALMETHOD.classOfListViewRecords>();
        //记录文件中读取的items
        List<GLOBALMETHOD.classOfListViewRecords> listStructOfFile = new List<GLOBALMETHOD.classOfListViewRecords>();
        //记录最后要写入文件的items
        List<GLOBALMETHOD.classOfListViewRecords> listStructOfWriteToFile = new List<GLOBALMETHOD.classOfListViewRecords>();
        /// <summary>
        /// 将合并后的list写入文件
        /// </summary>
        void writeListRecordsToFile()
        {
            FileStream fs = new FileStream(strFilePath, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            foreach (var v in listStructOfWriteToFile)
            {
                sw.WriteLine(encodeString(GLOBALMETHOD.classOfListViewRecords.ConvertStructToString(v)));
            }
            sw.Close();
        }
    
        /// <summary>
        /// 从文件中读取数据到list中
        /// </summary>
        void readListFromFile()
        {
            FileStream fs = new FileStream(strFilePath, FileMode.OpenOrCreate,FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            string str;
            while ((str = sr.ReadLine()) != null)
            {
				str = encodeString(str);
                listStructOfFile.Add(GLOBALMETHOD.classOfListViewRecords.ConvertStringToStruct(str));
            }
            sr.Close();
        }

		string strKey = "EventLogCSharp";
		string encodeString(string str)
		{
			//StringBuilder sb = new StringBuilder(str);
			//for (int i = 0; i < sb.Length; i++)
			//{
			//    sb[i] ^= strKey[i % strKey.Length];
			//}
			//return sb.ToString();
			return str;
		}

        /// <summary>
        /// 将listview中的记录读取到list中
        /// </summary>
        void addListViewToList()
        {
            foreach (var v in listViewShow.Items)
            {
                ListViewItem lvi;
                if ((lvi = v as ListViewItem) != null)
                {
                    GLOBALMETHOD.classOfListViewRecords s = new GLOBALMETHOD.classOfListViewRecords();
                    s.a_eventID = !string.IsNullOrEmpty(lvi.SubItems[0].Text) ? lvi.SubItems[0].Text : "";
                    s.b_timeGenerated = !string.IsNullOrEmpty(lvi.SubItems[1].Text) ? lvi.SubItems[1].Text : "";
                    s.c_strWeek = !string.IsNullOrEmpty(lvi.SubItems[2].Text) ? lvi.SubItems[2].Text : "";
                    s.d_duration = !string.IsNullOrEmpty(lvi.SubItems[3].Text) ? lvi.SubItems[3].Text : "";
                    s.e_context = !string.IsNullOrEmpty(lvi.SubItems[4].Text) ? lvi.SubItems[4].Text : "";
                    s.f_comment = !string.IsNullOrEmpty(lvi.SubItems[5].Text) ? lvi.SubItems[5].Text : "";
                    listStructOfListView.Add(s);
                }
                else
                {
                    MessageBox.Show("不该出现的错误");
                }
            }
        }

        /// <summary>
        /// 合并listview中的记录和从文件中读取的记录
        /// <para>合并到listStructOfWriteToFile中</para>
        /// </summary>
        void combineListViewAndFileList()
        {
            List<GLOBALMETHOD.classOfListViewRecords> list = new List<GLOBALMETHOD.classOfListViewRecords>();
            listStructOfWriteToFile.AddRange(listStructOfFile);

			foreach (var v in listStructOfListView)
			{
				bool bIsExist = false;
				for (int i = 0; i < listStructOfWriteToFile.Count;i++ )
				{
					if (v.a_eventID.Equals(listStructOfWriteToFile[i].a_eventID) &&
						v.b_timeGenerated.Equals(listStructOfWriteToFile[i].b_timeGenerated) &&
						v.c_strWeek.Equals(listStructOfWriteToFile[i].c_strWeek))
						/*v.d_duration.Equals(listStructOfWriteToFile[i].d_duration))
						 * 本字段是跟在关机之后的。当文件中的早期时间有持续时间，而事件日志中对应的持续时间被推掉了此字段就会不匹配。
						 * 如现在是2012-11-12 10:29:50，而9月11的某时刻有关机，有持续时间。但是
						 * 现在事件日志中没有那时刻对应的开机，所以列表中就不会出现关机的持续时间。而文件中有。就不会匹配。
						 */
					{
						if (!v.e_context.Equals(listStructOfWriteToFile[i].e_context))
						{
							listStructOfWriteToFile[i].e_context = v.e_context;
						}
                        if (!v.f_comment.Equals(listStructOfWriteToFile[i].f_comment))
                        {
                            v.f_comment = listStructOfWriteToFile[i].f_comment;
                        }
						bIsExist = true;
						break;
					}
				}
				if (!bIsExist)
				{
					list.Add(v);
				}
			}

            listStructOfWriteToFile.AddRange(list);
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            writeListRecordsToFile();
        }

		private void menuFromFile_Click(object sender, EventArgs e)
		{
			showListToListView(listStructOfFile);
            menuFromEventLog.Checked = menuTotal.Checked = toolStripButtonFromEventLog.Checked = toolStripButtonTotal.Checked = false;
		}

		private void menuFromEventLog_Click(object sender, EventArgs e)
		{
			showListToListView(listStructOfListView);
            menuFromFile.Checked = menuTotal.Checked = toolStripButtonFromFile.Checked = toolStripButtonTotal.Checked = false;
		}

		private void menuTotal_Click(object sender, EventArgs e)
		{
			showListToListView(listStructOfWriteToFile);
            menuFromFile.Checked = menuFromEventLog.Checked = toolStripButtonFromFile.Checked = toolStripButtonFromEventLog.Checked = false;
		}

		private void menuAbout_Click(object sender, EventArgs e)
		{
			string str = "软件名称 开关机详细信息查看\n作    者 独步云阶\n版    本 1.0.4.0\n编译时间 2013-5-15 12:43:05";
			MessageBox.Show(str, "关于", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);		
		}

		private void menuVersionLog_Click(object sender, EventArgs e)
		{
            FormLog fg = new FormLog();
            fg.ShowDialog();
		}

        private void listViewShow_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (listViewShow.SelectedItems.Count > 0)
            {
                FormInput fi = new FormInput(listViewShow.SelectedItems[0].SubItems[6].Text);
                if (DialogResult.OK == fi.ShowDialog())
                {
                    listViewShow.SelectedItems[0].SubItems[6].Text = fi.strComment;
                    addCommentToList(listStructOfWriteToFile, listViewShow.SelectedItems[0], fi.strComment);
                }
                
            }
        }

        /// <summary>
        /// 将备注在listWriteToFile中更新
        /// </summary>
        /// <param name="list"></param>
        /// <param name="lvi"></param>
        /// <param name="strComment"></param>
        void addCommentToList(List<GLOBALMETHOD.classOfListViewRecords> list,ListViewItem lvi,string strComment)
        {
            foreach (var v in list)
            {
                if (lvi.SubItems[0].Text.Equals(v.a_eventID)
                    && lvi.SubItems[1].Text.Equals(v.b_timeGenerated)
                    && lvi.SubItems[2].Text.Equals(v.c_strWeek))
                {
                    v.f_comment = strComment;
                    break;
                }
            }
        }

        private void menuOpenFile_Click(object sender, EventArgs e)
        {
            try
            {
                Process p = new Process();
                p.StartInfo.FileName = strFilePath;
                p.Start();
            }
            catch
            {
                MessageBox.Show("文件暂时不能打开！请检查此文件的位置是否正确！", "无法打开",
                    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }

        private void TSMI_NextPowerOn_Click(object sender, EventArgs e)
        {
            toolStripSplitButtonNext.Image = TSMI_NextPowerOn.Image;
			toolStripSplitButtonNext.ToolTipText = toolStripSplitButtonNext.Text = "下一个异常开机";
        }

        private void TSMI_NextPowerDown_Click(object sender, EventArgs e)
        {
            toolStripSplitButtonNext.Image = TSMI_NextPowerDown.Image;
			toolStripSplitButtonNext.ToolTipText = toolStripSplitButtonNext.Text = "下一个异常关机";
        }

        private void TSMI_NextPowerUpDown_Click(object sender, EventArgs e)
        {
            toolStripSplitButtonNext.Image = TSMI_NextPowerUpDown.Image;
			toolStripSplitButtonNext.ToolTipText = toolStripSplitButtonNext.Text = "下一个异常开关机";
        }

		private void TSMI_UpPowerOn_Click(object sender, EventArgs e)
		{
			toolStripSplitButtonUp.Image = TSMI_UpPowerOn.Image;
			toolStripSplitButtonUp.ToolTipText = toolStripSplitButtonUp.Text = "上一个异常开机";
        
		}

		private void TSMI_UpPowerDown_Click(object sender, EventArgs e)
		{
			toolStripSplitButtonUp.Image = TSMI_UpPowerDown.Image;
			toolStripSplitButtonUp.ToolTipText = toolStripSplitButtonUp.Text = "上一个异常关机";
		}

		private void TSMI_UpPowerUpDown_Click(object sender, EventArgs e)
		{
			toolStripSplitButtonUp.Image = TSMI_UpPowerUpDown.Image;
			toolStripSplitButtonUp.ToolTipText = toolStripSplitButtonUp.Text = "上一个异常开关机";
		}
		private void TSSBN_ButtonClick(object sender, EventArgs e)
		{
			if (toolStripSplitButtonNext.Text.ToString().Equals("下一个异常开机"))
			{
				JumpToNext(JumpToDirection.PowerOn);
			}
			else if (toolStripSplitButtonNext.Text.ToString().Equals("下一个异常关机"))
			{
				JumpToNext(JumpToDirection.PowerDown);
			}
			else if (toolStripSplitButtonNext.Text.ToString().Equals("下一个异常开关机"))
			{
				JumpToNext(JumpToDirection.PowerUpAndDown);
			}
		}

		private void TSSBU_ButtonClick(object sender, EventArgs e)
		{
			if (toolStripSplitButtonUp.Text.ToString().Equals("上一个异常开机"))
			{
				JumpToUp(JumpToDirection.PowerOn);
			}
			else if (toolStripSplitButtonUp.Text.ToString().Equals("上一个异常关机"))
			{
				JumpToUp(JumpToDirection.PowerDown);
			}
			else if (toolStripSplitButtonUp.Text.ToString().Equals("上一个异常开关机"))
			{
				JumpToUp(JumpToDirection.PowerUpAndDown);
			}
		}
		enum JumpToDirection
		{
			PowerOn,PowerDown,PowerUpAndDown
		}

		//跳转到下一个jtd中表示的（开关机）处
		private void JumpToNext(JumpToDirection jtd)
		{
			if (jtd == JumpToDirection.PowerDown)
			{
				JumpToString(1, new string[] { "非正常关机" });
			}
			else if (jtd == JumpToDirection.PowerOn)
			{
				JumpToString(1, new string[] { "非正常开机" });
			}
			else if (jtd == JumpToDirection.PowerUpAndDown)
			{
				JumpToString( 1,new string[]{"非正常开机","非正常关机"});
			}
		}
		//跳转到上一个jtd中表示的（开关机）处
		private void JumpToUp(JumpToDirection jtd)
		{
			if (jtd == JumpToDirection.PowerDown)
			{
				JumpToString(0, new string[] { "非正常关机" });
			}
			else if (jtd == JumpToDirection.PowerOn)
			{
				JumpToString(0, new string[] { "非正常开机" });
			}
			else if (jtd == JumpToDirection.PowerUpAndDown)
			{
				JumpToString(0, new string[] { "非正常关机","非正常开机" });
			} 
		}
		int JumpIndex = 0; //目前焦点所处位置
		/// <summary>
		/// 根据JumpDirection来决定在JumpIndex的上还是下查找说明为str的项
		/// </summary>
		/// <param name="str">下一个异常开机...</param>
		/// <param name="jd">方向</param>
		private void JumpToString( int jumpDirection,params string[] str)
		{
			int iItemCount = listViewShow.Items.Count;

			if (jumpDirection == 0)
			{
				JumpIndex = JumpIndex - 1 < 0 ? iItemCount - 1 : JumpIndex - 1;
				int j = 0; //只允许goto一次
			jls:
				int i;
				for (i = JumpIndex; i > 0; i--)
				{
					if (compareToStringArray(i, str))
					{
						return;
					}
				}
				if (i == 0 && j != 0)
				{
					return;
				}
				j++;
				JumpIndex = iItemCount - 1;
				goto jls;
			}
			else if (jumpDirection == 1)
			{
				JumpIndex = JumpIndex + 1 >= iItemCount ? 0 : JumpIndex + 1;
				int j = 0;
			JLS:
				int i;
				for (i = JumpIndex; i < iItemCount; i++)
				{
					if (compareToStringArray(i,str))
					{
						return;
					}
				}
				if (i == iItemCount && j != 0)
				{
					return;
				}
				j++;
				JumpIndex = 0;
				goto JLS;
			}
		}

		//比较listView的i行第5个元素的内容和strArray比较。如果相同，选中并显示。同时显示是第几个异常开关机以及总异常数
		bool compareToStringArray(int i, string[] strArray)
		{
			if (strArray.Length == 1)
			{
				if (listViewShow.Items[i].SubItems[4].Text.Equals(strArray[0]))
				{
					listViewShow.Items[i].Selected = true;
					listViewShow.Items[i].EnsureVisible();
					JumpIndex = i;
					//显示当前选择的是第几个异常开机/关机
					int iSerial = 0;
					List<int> listTemp = strArray[0].Equals("非正常关机") ? listExcepPowerDown : listExcepPowerOn;

					if ((iSerial = listTemp.FindIndex(j => j == Convert.ToInt32(listViewShow.Items[i].SubItems[5].Text))) != -1)
					{
						lbSerial.Text = (iSerial + 1).ToString() + "/" + listTemp.Count.ToString();
					}		
					return true;
				}
			}
			else if (strArray.Length == 2)	//下一个非正常开机或者关机
			{
				if (listViewShow.Items[i].SubItems[4].Text.Equals(strArray[0])
					|| listViewShow.Items[i].SubItems[4].Text.Equals(strArray[1]))
				{
					listViewShow.Items[i].Selected = true;
					listViewShow.Items[i].EnsureVisible();
					JumpIndex = i;
					//显示当前选择的是第几个异常开机/关机
					int iSerial = 0;
					List<int> listTemp = listViewShow.Items[i].SubItems[4].Text.Equals("非正常关机") ? listExcepPowerDown : listExcepPowerOn;

					if ((iSerial = listTemp.FindIndex(j => j == Convert.ToInt32(listViewShow.Items[i].SubItems[5].Text))) != -1)
					{
						lbSerial.Text = (iSerial + 1).ToString() + "/" + listTemp.Count.ToString();
					}
					return true;
				}
			}


			return false;
		}


		/// <summary>
		/// 保存异常开机的序号
		/// </summary>
		List<int> listExcepPowerOn;
		List<int> listExcepPowerDown;
		//显示异常开关机的次数
		void showExceptionPowerTimes()
		{
			listExcepPowerOn = new List<int>();
			listExcepPowerDown = new List<int>();

			for (int i = 0; i < listViewShow.Items.Count;i++ )
			{
				if (listViewShow.Items[i].SubItems[4].Text.Equals("非正常开机"))
				{
					listExcepPowerOn.Add(Convert.ToInt32(listViewShow.Items[i].SubItems[5].Text));
				}
				else if (listViewShow.Items[i].SubItems[4].Text.Equals("非正常关机"))
				{
					listExcepPowerDown.Add(Convert.ToInt32(listViewShow.Items[i].SubItems[5].Text));
				}
			}

			lbPowerOn.Text = "非正常开机次数："+ listExcepPowerOn.Count.ToString();
			lbPowerDown.Text = "非正常关机次数：" + listExcepPowerDown.Count.ToString();
		}

	}


	public class EventLogOfSystem
	{
		private EventLogEntryCollection eventCollection;
		private EventLog systemEvent;

		public struct EventCode
		{
			public static int Start = 6009;
			public static int Shutdown = 6006;
		}

		public EventLogOfSystem()
		{
			systemEvent = new EventLog();
			systemEvent.Log = "System";
			eventCollection = systemEvent.Entries;
		}

		public struct structDataOfEventLog
		{
			public int EventID;
			public DateTime timeGenerated;
		}

		public List<structDataOfEventLog> m_listStructDataOfEventLog;

		public void GetRecords(params int[] iNumbers)
		{
			m_listStructDataOfEventLog = new List<structDataOfEventLog>();
			foreach (EventLogEntry v in systemEvent.Entries)
			{
				EventLogEntry entry = v;
				foreach (var i in iNumbers)
				{

					if (v.EventID == i)
					{
						structDataOfEventLog s = new structDataOfEventLog();
						s.timeGenerated = v.TimeGenerated;
						s.EventID = v.EventID;

						m_listStructDataOfEventLog.Add(s);
					}
				}
			}
		}


		// 		public EventLogEntryCollection LoadEventLog()
		// 		{
		// 			EventLog systemEvent = new EventLog();
		// 			systemEvent.Log = "System";
		// 			eventCollection = systemEvent.Entries;
		// 			return eventCollection;
		//			int length = eventCollection.Count;
		//			EventLogEntry entry = eventCollection[c];
		// 			string[] title ={
		// 　　　entry.EntryType.ToString(),
		// 　　　entry.TimeGenerated.ToLongDateString(),
		// 　　　entry.TimeGenerated.ToLongTimeString(),
		// 　　　entry.Source,
		// 　　　entry.Category,
		// 　　　//entry.EventID.ToString(),
		//    entry.InstanceId.ToString(),
		// 　　　entry.UserName,
		// 　　　entry.MachineName
		// 　　};
		// 			for (int j = 0; j < title.Length; j++)
		// 			{
		// 				//Console.WriteLine(title[j]);
		// 				MessageBox.Show(title[j]);
		// 			}
		//Console.WriteLine("n" + eventCollection[c].Message);
		//		}

		// 		public string DisplayEventCount()
		// 		{
		// 			return (eventCollection.Count.ToString());
		// 		}
	}
}
